package rabbitmq.rpc;

import com.rabbitmq.client.*;
import rabbitmq.constant.Constants;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * RPC服务端
 * 1.接受请求
 * 2.发送响应
 */
public class PpcServer {
    public static void main(String[] args) throws IOException, TimeoutException {
        //建立连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        //设置ip
        connectionFactory.setHost(Constants.HOST);
        //设置端口  需要提前开放端口号
        connectionFactory.setPort(Constants.PORT);
        //设置账号
        connectionFactory.setUsername(Constants.USERNAME);
        //设置密码
        connectionFactory.setPassword(Constants.PASSWORD);
        //设置虚拟机 要操作哪个虚拟机
        connectionFactory.setVirtualHost(Constants.VIRTUAL_HOST);
        //创建连接
        Connection connection = connectionFactory.newConnection();
        //2.创建信道
        Channel channel = connection.createChannel();
        //接受请求(也就是消费) 一次接受一个消息
        channel.basicQos(1);
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String request = new String(body);
                System.out.println("接受到请求：" + request);
                //响应
                String response = "针对request：" + request + "响应成功！！！！";
                AMQP.BasicProperties props = new AMQP.BasicProperties.Builder()
                        .correlationId(properties.getCorrelationId())
                        .build();
                channel.basicPublish("", Constants.RPC_RESPONSE_QUEUE, props, response.getBytes());
                //进行手动确认
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        };
        channel.basicConsume(Constants.RPC_REQUEST_QUEUE, false, consumer);
    }
}
